const gradeModel = require('../models/grade.model');
const db = require('../config/db');

// 获取学生所有成绩概览
exports.getStudentGrades = async (req, res) => {
  console.log("getStudentGrades called() 0:",req.user.userId);
  try {
    const studentId = req.user.userId;
    const grades = await gradeModel.getGradesByStudentId(studentId);
    console.log("getStudentGrades called() 1:", grades);

    res.json(grades);
  } catch (err) {
    console.error('获取成绩失败:', err);
    res.status(500).json({ message: '获取成绩失败' });
  }
};

// 获取课程详细成绩
exports.getCourseGradeDetail = async (req, res) => {
  try {
    const { courseId } = req.params;
    const studentId = req.user.id;

    const gradeDetail = gradeModel.findCourseGrade(studentId, courseId);

    if (!gradeDetail) {
      return res.status(404).json({ message: '未找到成绩记录' });
    }

    // 添加实验详情
    const detailedGrades = gradeDetail.experimentGrades.map(grade => ({
      id: grade.experimentId,
      title: grade.title,
      parts: grade.parts,
      totalScore: grade.totalScore
    }));

    res.json({
      courseId: gradeDetail.courseId,
      year: gradeDetail.year,
      semester: gradeDetail.semester,
      finalGrade: gradeDetail.finalGrade,
      experiments: detailedGrades
    });
  } catch (err) {
    console.error('获取详细成绩失败:', err);
    res.status(500).json({ message: '获取详细成绩失败' });
  }
};

// 获取班级成绩数据
exports.getClassGrades = async (req, res) => {
  try {
    const classId = req.params.classId;
    console.log("getClassGrades called()", classId);
    // 1. 获取班级基本信息
    const [classInfo] = await db.query(
      `SELECT id, name, course_id FROM classes WHERE id = ?`,
      [classId]
    );
    
    if (classInfo.length === 0) {
      return res.status(404).json({ message: '班级不存在' });
    }
    
    const className = classInfo[0].name;
    const courseId = classInfo[0].course_id;

    console.log("getClassGrades called() 2:", courseId, className);
    
    // 2. 获取班级关联的实验信息
    const [experiments] = await db.query(
      `SELECT 
          e.id, 
          e.title,
          COUNT(ec.experiment_id) AS class_count
       FROM experiment_classes ec
       JOIN experiments e ON ec.experiment_id = e.id
       WHERE ec.class_id = ?
       GROUP BY ec.experiment_id`,
      [classId]
    );

    console.log("getClassGrades called() 3:", experiments);

    
    // 3. 获取班级学生列表
    const [students] = await db.query(
      `SELECT 
          s.id, 
          s.s_no, 
          s.s_name,
          s.class AS class_name
       FROM class_students cs
       JOIN students s ON cs.student_id = s.id
       WHERE cs.class_id = ?`,
      [classId]
    );
    
    if (students.length === 0) {
      return res.json({
        classId,
        className,
        experiments,
        students: [],
        grades: []
      });
    }
    
    const studentIds = students.map(s => s.id);
    const experimentIds = experiments.map(e => e.id);
    
    // 4. 获取学生成绩数据
    const [rawGrades] = await db.query(
      `SELECT 
          es.student_id,
          es.experiment_id,
          ROUND(SUM(es.score * ec.proportion / 100), 1) AS score       FROM experiment_scores es
       JOIN experiment_criteria ec ON es.criteria_id = ec.id
       JOIN experiments e ON es.experiment_id = e.id
       WHERE es.student_id IN (?)
         AND es.experiment_id IN (?)
       GROUP BY es.student_id, es.experiment_id`,
      [studentIds, experimentIds]
    );

    // 5. 构建学生成绩映射
    const gradeMap = rawGrades.reduce((map, grade) => {
      if (!map[grade.student_id]) map[grade.student_id] = {};
      map[grade.student_id][grade.experiment_id] = grade.score;
      return map;
    }, {});
    
    // 6. 计算总分并构建最终结构
    const structuredStudents = students.map(student => {
      const studentGrades = gradeMap[student.id] || {};
      
      // 计算总分 - 确保是数字类型
      const totalScore = Object.values(studentGrades).reduce(
        (sum, score) => sum + (parseFloat(score) || 0), 
        0
      );
      
      return {
        ...student,
        grades: studentGrades,
        total_score: totalScore
      };
    });
    
    res.json({ experiments, students: structuredStudents });  
  } catch (err) {
    console.error('获取班级成绩失败:', err);
    res.status(500).json({ message: '获取班级成绩失败' });
  }
};

// 获取批改数据
exports.getGradingData = async (req, res) => {
  try {
    const { classId, experimentId } = req.params;
    
    // 1. 获取评分标准
    const [criteria] = await db.query(
      `SELECT id, name, proportion 
       FROM experiment_criteria
       WHERE experiment_id = ?`,
      [experimentId]
    );

    // 2. 获取班级学生
    const [students] = await db.query(
      `SELECT s.id, s.s_no, s.s_name
       FROM class_students cs
       JOIN students s ON cs.student_id = s.id
       WHERE cs.class_id = ?`,
      [classId]
    );

    // 3. 获取现有成绩
    const [existingGrades] = await db.query(
      `SELECT student_id, criteria_id, score
       FROM experiment_scores
       WHERE experiment_id = ? 
         AND student_id IN (?)`,
      [experimentId, students.map(s => s.id)]
    );

    // 4. 构建响应数据
    const gradingData = students.map(student => {
      const grades = {};
      criteria.forEach(c => {
        const grade = existingGrades.find(
          g => g.student_id === student.id && g.criteria_id === c.id
        );
        grades[c.id] = grade ? grade.score : null;
      });
      
      return {
        id: student.id,
        s_no: student.s_no,
        s_name: student.s_name,
        grades
      };
    });

    res.json({
      criteria,
      gradingData
    });
  } catch (err) {
    console.error('获取批改数据失败:', err);
    res.status(500).json({ message: '获取批改数据失败' });
  }
};

// 更新成绩
exports.updateGrades = async (req, res) => {
  try {
    const { studentId, experimentId, criteriaId, score } = req.body;
    
    // 检查成绩是否有效
    if (score === null || score === undefined) {
      return res.status(400).json({ message: '无效的成绩值' });
    }
    
    // 检查记录是否存在
    const [existing] = await db.query(
      `SELECT id FROM experiment_scores
       WHERE student_id = ? 
         AND experiment_id = ?
         AND criteria_id = ?`,
      [studentId, experimentId, criteriaId]
    );
    
    if (existing.length > 0) {
      // 更新现有记录
      await db.query(
        `UPDATE experiment_scores 
         SET score = ?, status = '已批改'
         WHERE id = ?`,
        [score, existing[0].id]
      );
    } else {
      // 插入新记录
      await db.query(
        `INSERT INTO experiment_scores 
         (student_id, experiment_id, criteria_id, score, status)
         VALUES (?, ?, ?, ?, '已批改')`,
        [studentId, experimentId, criteriaId, score]
      );
    }
    
    res.json({ success: true });
  } catch (err) {
    console.error('更新成绩失败:', err);
    res.status(500).json({ message: '更新成绩失败' });
  }
};